package com.easy.frame.servers.sys.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easy.frame.base.basic.exception.ServiceException;
import com.easy.frame.base.basic.util.AuthUtils;
import com.easy.frame.servers.sys.entity.SysFile;
import com.easy.frame.servers.sys.file.FileClient;
import com.easy.frame.servers.sys.mapper.SysFileMapper;
import com.easy.frame.servers.sys.service.SysFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * OBS对象存储实现类 服务实现类
 *
 * @author tp
 * @since 2021-01-19
 */
@Service
public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFile> implements SysFileService {

    private static final List<String> CONTENT_TYPES = Arrays.asList("image/jpeg", "image/gif", "image/png", "application/vnd.android.package-archive");
    private static final Logger LOGGER = LoggerFactory.getLogger(SysFileServiceImpl.class);

    @Resource
    private FileClient fileClient;

    @Resource
    private SysFileMapper sysFileMapper;

    /**
     * 文件上传
     */
    @Override
    public SysFile uploadFile(MultipartFile file) {
        String contype = file.getContentType();
        String originalFilename = file.getOriginalFilename();
        if (!CONTENT_TYPES.contains(contype)) {
            LOGGER.info("文件类型出错" + originalFilename);
            throw new ServiceException("文件类型出错【文件名为" + originalFilename + "】，请传正确的文件");
        }
        //获取图片名称，作为上传文件名参数
        String objectKey = file.getOriginalFilename();
        // 使用访问OBS（暂时否是使用ifm2桶）
        String fileUrl = fileClient.uploadFile("easyFrame", objectKey, file);

        //将图片信息封装起来保存，方便前端回显调用
        SysFile sysFile = new SysFile();
        sysFile.setName(originalFilename);
        sysFile.setType(contype);
        sysFile.setUrl(fileUrl);
        sysFile.setBucket("easyFrame");
        sysFile.setObjectKey(objectKey);
        sysFile.setCreateBy(AuthUtils.getCurrentUserId());
        sysFile.setUpdateBy(AuthUtils.getCurrentUserId());
        sysFileMapper.insert(sysFile);
        return sysFile;
    }

    /**
     * 文件下载
     */
    @Override
    public SysFile exportFile(SysFile sysFile) throws IOException {
        fileClient.downLoadFile(sysFile);
        return sysFile;
    }
}
